import { message } from "ant-design-vue";
import router from "./router";
import { userLoginStore } from "./stores/userLoginStore";

//是否为首次获取用户信息
let isFirstGetUserInfo=true;
router.beforeEach(async (to, from, next) => { 
   const loginUserStore=userLoginStore();
   let loginUser=loginUserStore.loginUser;
   //确保页面刷新时，首次加载时，能等待后端返回用户信息
   if(isFirstGetUserInfo) {
   await loginUserStore.getLoginUser();
   loginUser=loginUserStore.loginUser;
   isFirstGetUserInfo=false;
   }
   const toUrl=to.fullPath;
   //自定义权限校验规则
   if(toUrl.startsWith('/admin')){
      if(!loginUserStore||loginUserStore.loginUser.userRole!='admin'){
         message.error('没有权限');
         next(`/user/login?redirect=${to.fullPath}`);
         return
      }
   }
   next();
   
});